import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:msal_auth/msal_auth.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../api/interface/login_api.dart';
import '../../api/request/response_data.dart';
import '../../basic/base_info.dart';
import '../../config/const.dart';
import '../../moudle/message.dart';
import '../../utils/string_tool.dart';
import '../../widget/common_widget.dart';
import '../index_drawer_page.dart';

class MailRegister extends StatefulWidget {
  final bool isBanck;
  const MailRegister({super.key, this.isBanck = false});

  @override
  State<MailRegister> createState() => _MailRegisterState();
}

class _MailRegisterState extends State<MailRegister> {

  String? firstName;
  String? lastName;
  String? password;
  String? surePassword;
  bool isDisabled = true;
  bool isSureDisabled = true;

  bool isDone = false;

  TextEditingController firstNameController = TextEditingController();
  TextEditingController lastNameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController surePasswordController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  getIsDone(){
    if(lastName == null || lastName!.isEmpty || firstName == null || firstName!.isEmpty || password == null || password!.isEmpty || surePassword == null || surePassword!.isEmpty){
      isDone = false;
    }else{
      isDone = true;
    }
    if(mounted){
      setState(() {});
    }
  }

  _register()async{

    if(password!.length<6 || surePassword!.length < 6){
      showToast(pwd_length_less.tr);
      return;
    }
    if(password! != surePassword!){
      showToast(pwd_sure_pwd_error.tr);
      return;
    }
    Map<String,dynamic> data = {
      'nickname':'$firstName$lastName',
      'firstName':firstName,
      'lastName':lastName,
      'password':password,
    };
    showLoading();
    ResponseData res = await LoginAPI.userEdit(data);
    hideLoading();
    if(res.code == 200){
      Navigator.pushAndRemoveUntil(context, PageRouteBuilder(
          settings: const RouteSettings(name: "index"),
          pageBuilder:
              (BuildContext context, Animation animation,
              Animation secondaryAnimation) {
            return const DrawerIndexPage();
          }), (route) => false);
    }
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      body: SingleChildScrollView(
        child: Container(
          height: 1.sh,
          padding: EdgeInsets.symmetric(horizontal: 48.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(height:160.w,),
              Container(
                alignment: Alignment.centerLeft,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Visibility(child: GestureDetector(
                      onTap: (){
                        FocusScope.of(context).requestFocus(FocusNode());
                        Navigator.of(context).pop();
                      },
                      child: Container(
                        child: Image.asset('assets/login/back.png',width: 56.w,),
                      ),
                    ),visible: widget.isBanck,),
                    SizedBox(height: 28.w,),
                    Container(
                      child: Text('Sign Up'.tr,style: TextStyle(
                          color: Colors.white,
                          fontSize: 48.sp,
                          fontWeight: FontWeight.w600
                      ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                    )
                  ],
                ),
              ),
              SizedBox(height: 90.w,),
              //用户名
              Container(
                width: 670.w,
                height: 108.w,
                padding: EdgeInsets.symmetric(horizontal: 30.w),
                decoration: BoxDecoration(
                    border: inputBorder,
                    borderRadius: BorderRadius.circular(20.w)
                ),
                child:  Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(child: TextField(
                      //控制器
                      textInputAction: TextInputAction.done,
                      controller: firstNameController,
                      maxLength: 20,
                      maxLines: 1,
                      //是否自动更正
                      autocorrect: true,
                      //是否自动对焦
                      autofocus: false,
                      style: inputStyle,
                      inputFormatters: [

                      ],
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                        hintText: 'First Name'.tr,
                        hintStyle: inputHitStyle,
                        counterText: "",
                        border: OutlineInputBorder(
                            borderSide: BorderSide.none),
                      ),
                      onChanged: (val){
                        setState(() {
                          firstName = val.trim();
                        });
                        getIsDone();
                      },
                    )),
                    SizedBox(width: 20.w,),
                    Visibility(visible: firstName!=null&&firstName!.isNotEmpty,
                      child: GestureDetector(
                        onTap: (){
                          setState(() {
                            firstNameController.text = '';
                            firstName = null;
                          });
                          getIsDone();
                        },
                        child: Container(
                          child: inputImg,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 32.w,),
              //用户名
              Container(
                width: 670.w,
                height: 108.w,
                padding: EdgeInsets.symmetric(horizontal: 30.w),
                decoration: BoxDecoration(
                    border: inputBorder,
                    borderRadius: BorderRadius.circular(20.w)
                ),
                child:  Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(child: TextField(
                      //控制器
                      textInputAction: TextInputAction.done,
                      controller: lastNameController,
                      maxLength: 20,
                      maxLines: 1,
                      //是否自动更正
                      autocorrect: true,
                      //是否自动对焦
                      autofocus: false,
                      style: inputStyle,
                      inputFormatters: [

                      ],
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                        hintText: 'Last Name'.tr,
                        hintStyle: inputHitStyle,
                        counterText: "",
                        border: OutlineInputBorder(
                            borderSide: BorderSide.none),
                      ),
                      onChanged: (val){
                        setState(() {
                          lastName = val.trim();
                        });
                        getIsDone();
                      },
                    )),
                    SizedBox(width: 20.w,),
                    Visibility(visible: lastName!=null&&lastName!.isNotEmpty,
                      child: GestureDetector(
                        onTap: (){
                          setState(() {
                            lastNameController.text = '';
                            lastName = null;
                          });
                          getIsDone();
                        },
                        child: Container(
                          child: inputImg,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 32.w,),
              //密码
              Container(
                width: 670.w,
                height: 108.w,
                padding: EdgeInsets.symmetric(horizontal: 30.w),
                decoration: BoxDecoration(
                    border: inputBorder,
                    borderRadius: BorderRadius.circular(20.w)
                ),
                child:  Row(
                  children: [
                    Expanded(child: TextField(
                      //控制器
                      controller: passwordController,
                      // maxLength: 11,
                      maxLines: 1,
                      //是否自动更正
                      autocorrect: true,
                      //是否自动对焦
                      autofocus: false,
                      obscureText: isDisabled, //是否是密码
                      style: inputStyle,
                      decoration:  InputDecoration(
                        //                hintText: "请输入用户名",
                        contentPadding: EdgeInsets.zero,
                        hintText: pwd_hintText.tr,
                        hintStyle: inputHitStyle,
                        counterText: "",
                        border: const OutlineInputBorder(
                            borderSide: BorderSide.none),
                      ),
                      onChanged: (val) {
                        setState(() {
                          password = val.trim();
                        });
                        getIsDone();
                      },
                    )),
                    SizedBox(width: 20.w,),
                    GestureDetector(
                      onTap: (){
                        setState(() {
                          isDisabled = !isDisabled;
                        });
                      },
                      child: Container(
                        child: Image.asset(!isDisabled?'assets/common/input_show.png':'assets/common/input_hide.png',width: 48.w,),
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 40.w,),
              //确认密码
              Container(
                width: 670.w,
                height: 108.w,
                padding: EdgeInsets.symmetric(horizontal: 30.w),
                decoration: BoxDecoration(
                    border: inputBorder,
                    borderRadius: BorderRadius.circular(20.w)
                ),
                child:  Row(
                  children: [
                    Expanded(child: TextField(
                      //控制器
                      controller: surePasswordController,
                      // maxLength: 11,
                      maxLines: 1,
                      //是否自动更正
                      autocorrect: true,
                      //是否自动对焦
                      autofocus: false,
                      obscureText: isSureDisabled, //是否是密码
                      style: inputStyle,
                      decoration:  InputDecoration(
                        //                hintText: "请输入用户名",
                        contentPadding: EdgeInsets.zero,
                        hintText: ensure_pwd_hintText.tr,
                        hintStyle: inputHitStyle,
                        counterText: "",
                        border: const OutlineInputBorder(
                            borderSide: BorderSide.none),
                      ),
                      onChanged: (val) {
                        setState(() {
                          surePassword = val.trim();
                        });
                        getIsDone();
                      },
                    )),
                    SizedBox(width: 20.w,),
                    GestureDetector(
                      onTap: (){
                        setState(() {
                          isSureDisabled = !isSureDisabled;
                        });
                      },
                      child: Container(
                        child: Image.asset(!isSureDisabled?'assets/common/input_show.png':'assets/common/input_hide.png',width: 48.w,),
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 90.w,),
              GestureDetector(
                onTap: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  getIsDone();
                  if(isDone==false){
                    return;
                  }
                  _register();
                },
                child: Container(
                  height: 108.w,
                  width: 670.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: isDone? themeColor:themeDisableColor,
                      borderRadius: BorderRadius.circular(20.w)
                  ),
                  child: Text('Continue'.tr,style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),),
                ),
              ),
              Expanded(child: GestureDetector(
                onTap: (){
                  FocusScope.of(context).requestFocus(FocusNode());
                  getIsDone();
                  FocusScope.of(context).requestFocus(FocusNode());
                },
                child: Container(
                  color: Colors.transparent,
                  width: 1.sw,
                ),
              )),
              // Visibility(visible: true,child: Column(
              //   children: [
              //     Container(
              //       padding: EdgeInsets.symmetric(horizontal: 48.w),
              //       height: 48.w,
              //       child: Stack(
              //         children: [
              //           Center(child: Container(
              //             height: 1.w,
              //             width: 480.w,
              //             color: Color(0xff484848),
              //           ),),
              //           Center(
              //             child: Container(
              //               alignment: Alignment.center,
              //               height: 48.w,
              //               width: 48.w,
              //               decoration: BoxDecoration(
              //                   color: Color(0xff484848),
              //                   borderRadius: BorderRadius.circular(48.w)
              //               ),
              //               child: Text('or',style: TextStyle(
              //                   color: Color(0xff939393),
              //                   fontSize: 24.sp
              //               ),),
              //             ),
              //           )
              //         ],
              //       ),
              //     ),
              //     Container(
              //       margin: EdgeInsets.only(top: 32.w),
              //       child: Row(
              //         mainAxisAlignment: MainAxisAlignment.center,
              //         children: [
              //           Visibility(visible: true,child: GestureDetector(
              //             onTap: ()async{
              //               _loginAPPByGoogle();
              //             },
              //             child: Container(
              //               width: 108.w,
              //               height: 108.w,
              //               decoration: BoxDecoration(
              //                   color: Color(0xff2B2B2B),
              //                   borderRadius: BorderRadius.circular(108.w)
              //               ),
              //               child: Row(
              //                 mainAxisAlignment: MainAxisAlignment.center,
              //                 crossAxisAlignment: CrossAxisAlignment.center,
              //                 children: [
              //                   Image.asset('assets/login/login_google.png',width: 40.w,),
              //                 ],
              //               ),
              //             ),
              //           ),),
              //           SizedBox(width: 64.w,),
              //           Visibility(visible: true,child: GestureDetector(
              //             onTap: ()async{
              //               _loginAppByMsal();
              //             },
              //             child: Container(
              //               width: 108.w,
              //               height: 108.w,
              //               decoration: BoxDecoration(
              //                   color: Color(0xff2B2B2B),
              //                   borderRadius: BorderRadius.circular(108.w)
              //               ),
              //               child: Row(
              //                 mainAxisAlignment: MainAxisAlignment.center,
              //                 crossAxisAlignment: CrossAxisAlignment.center,
              //                 children: [
              //                   Image.asset('assets/login/login_wr.png',width: 40.w,),
              //                 ],
              //               ),
              //             ),
              //           ),),
              //           Visibility(visible: Platform.isIOS,child: GestureDetector(
              //             onTap: ()async{
              //               _loginAPPByApple();
              //             },
              //             child: Container(
              //               width: 108.w,
              //               height: 108.w,
              //               margin: EdgeInsets.only(left: 64.w),
              //               decoration: BoxDecoration(
              //                   color: Color(0xff2B2B2B),
              //                   borderRadius: BorderRadius.circular(108.w)
              //               ),
              //               child: Row(
              //                 mainAxisAlignment: MainAxisAlignment.center,
              //                 crossAxisAlignment: CrossAxisAlignment.center,
              //                 children: [
              //                   Image.asset('assets/login/login_apple.png',width: 40.w,),
              //                 ],
              //               ),
              //             ),
              //           ),),
              //         ],
              //       ),
              //     )
              //   ],
              // ),),
              // SizedBox(height: 84.w,),
              // Container(
              //   child: Row(
              //     mainAxisAlignment: MainAxisAlignment.center,
              //     children: [
              //       GestureDetector(
              //         onTap: (){
              //           Navigator.of(context).pushNamed('RegisterPage');
              //         },
              //         child: Container(
              //           child: Text('Create an account',style: TextStyle(
              //               color: Color(0xff576EFF),
              //               fontSize: 28.sp,
              //               fontWeight: FontWeight.w600
              //           ),),
              //         ),
              //       ),
              //       Container(
              //         width: 6.w,
              //         height: 6.w,
              //         decoration: BoxDecoration(
              //             color: Colors.white,
              //             borderRadius: BorderRadius.circular(6.w)
              //         ),
              //         margin: EdgeInsets.symmetric(horizontal: 20.w),
              //       ),
              //       GestureDetector(
              //         onTap: (){
              //           Navigator.of(context).pushNamed('ForgetPwd',arguments: 1);
              //         },
              //         child: Container(
              //           child: Text('Fogot your password？',style: TextStyle(
              //               color: Color(0xff576EFF),
              //               fontSize: 28.sp,
              //               fontWeight: FontWeight.w600
              //           ),),
              //         ),
              //       )
              //     ],
              //   ),
              // ),
              SizedBox(height: ScreenUtil().bottomBarHeight > 0? ScreenUtil().bottomBarHeight+20.w:48.w,),
            ],
          ),
        ),
      ),
    );
  }

  _loginAPPByApple()async{
    AuthorizationCredentialAppleID appleIdCredential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName
      ],
    );
    String? identityToken = appleIdCredential.identityToken;
    // final oAuthProvider = OAuthProvider('apple.com');
    print('identityToken ==user ${identityToken.toString()}');
    // final credential = oAuthProvider.credential(
    //   idToken: appleIdCredential.identityToken,
    //   accessToken: appleIdCredential.authorizationCode,
    // );
    if(identityToken != null ){
      _getCodeSignOrLogin('3',identityToken!);
    }
    // try{
    //   print('_loginAPPByApple ==user 123');
    //   final UserCredential? user = (await FirebaseAuth.instance.signInWithCredential(credential));
    //   print('_loginAPPByApple ==user ${user.toString()}');
    //   if(identityToken != null){
    //
    //   }
    // }catch(e){
    //   print('error == '+e.toString());
    // }
  }

  _loginAPPByGoogle()async{
    const List<String> scopes = <String>[
      'email',
    ];
    GoogleSignIn _googleSignIn = GoogleSignIn(
        scopes: scopes
    );
    GoogleSignInAccount? account = await _googleSignIn.signIn();

    GoogleSignInAuthentication? authentication = await account?.authentication;

    StringTool.long_p('authenticationaccessToken ==='+authentication!.accessToken.toString());
    StringTool.long_p('authenticationidToken ==='+authentication!.idToken.toString());
    if(authentication != null && authentication!.idToken != null){
      _getCodeSignOrLogin('1',authentication!.idToken!);
    }

    //  final credential =  GoogleAuthProvider.credential(accessToken: authentication?.accessToken, idToken: authentication?.idToken);
    //
    // UserCredential user = await FirebaseAuth.instance.signInWithCredential(credential);
    //
    //
    //  print('_googleSignIn ==='+user.toString());
  }

  _loginAppByMsal()async{
    // MsalMobileClient msalAuth = await MsalMobileClient.init(
    //   clientId: _clientId,
    //   scopes: _scopes,
    //   androidConfig: AndroidConfig(
    //     configFilePath: 'assets/msal_config.json',
    //     tenantId: _tenantId,
    //   ),
    //   iosConfig: IosConfig(authority: _authority),
    // );
    // try {
    //   final user = await msalAuth.acquireToken();
    //   print('User data: ${user?.toJson()}');
    // } on MsalException catch (e) {
    //   print('Msal exception with error: ${e.errorMessage}');
    // } catch (e) {
    //   print(e.toString());
    // }
    // return;
    getToken();
  }

  Future<MsalAuth> getMsalAuth() async {
    return MsalAuth.createPublicClientApplication(
      clientId: clientId,
      scopes: scopes,
      androidConfig: AndroidConfig(
        configFilePath: 'assets/msal_config.json',
        // tenantId: _tenantId
      ),
      iosConfig: IosConfig(authority: iosAuth,authMiddleware: AuthMiddleware.webView),);
  }
  Future<void> getToken() async {
    try {
      final msalAuth = await getMsalAuth();
      final user = await msalAuth.acquireToken();
      if(user != null){
        _getCodeSignOrLogin('2',user!.idToken);
      }
    } on MsalException catch (e) {
      print('Msal exception with error: ${e.errorMessage}');
    } catch (e) {
      print(e.toString());
    }
  }

  Future<void> getTokenSilently() async {
    try {
      final msalAuth = await getMsalAuth();
      final user = await msalAuth.acquireTokenSilent();
      print('User data: ${user?.toJson()}');
    } on MsalException catch (e) {
      print('Msal exception with error: ${e.errorMessage}');
    } catch (e) {
      print(e.toString());
    }
  }

  _getCodeSignOrLogin(String loginType,String token)async{
    //google,microsoft,apple
    Map<String,dynamic> data = {
      'loginType':loginType,
      'token':token
    };
    showLoading();
    ResponseData res = await LoginAPI.getCodeSignOrLogin(data);
    hideLoading();
    if(res.code == 200){
      LocalBaseInfo.setToken(res.data['token']);
      bool updateUser = res.data['updateUser']?? true;
      if(!updateUser){
        Navigator.of(context).pushNamed('MailRegister',arguments: true);
      }else{
        Navigator.pushAndRemoveUntil(context, PageRouteBuilder(
            settings: const RouteSettings(name: "index"),
            pageBuilder:
                (BuildContext context, Animation animation,
                Animation secondaryAnimation) {
              return const DrawerIndexPage();
            }), (route) => false);
      }
    }
  }
}
